package com.tuosha.controller;


import com.tuosha.base.controller.BaseController;
import com.tuosha.constant.Constants;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("upload")
public class FileUploadHandler extends BaseController {

    @ResponseBody
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public Object fileUpload(@RequestParam("file") CommonsMultipartFile file) throws IOException {
        long  startTime=System.currentTimeMillis();
        System.out.println("fileName："+file.getOriginalFilename());
//        String path="D:/"+file.getOriginalFilename();
        String realPath=request.getSession().getServletContext().getRealPath("/")+"uploads\\";
        System.out.println(realPath+"这个是realPath");
        String path = this.getClass().getClassLoader().getResource("").getPath();
        String name = file.getOriginalFilename();

        System.out.println(realPath+file.getOriginalFilename());
        File newFile=new File(realPath,name);
        if(!newFile.getParentFile().exists()){
            newFile.getParentFile().mkdir();
        }
        if(newFile.exists()){
            newFile.delete();
        }
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        file.transferTo(newFile);
        long  endTime=System.currentTimeMillis();
        System.out.println("方法二的运行时间："+String.valueOf(endTime-startTime)+"ms");
        String a=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/uploads/"+name;

        return putMsgToJsonString(Constants.WebSite.SUCCESS,"提交成功！",0,a);

    }

}